<?php
/**
 * Created by PhpStorm.
 * User: Duyonggao
 * Date: 2017/8/2 0002
 * Time: 上午 9:30
 */

namespace app\controllers;


use app\models\SiteData;
use app\models\SiteInfo;
use app\utils\TaoBaoApi;
use utils\Comm;
use utils\Curl;
use utils\HelperSearch;
use utils\TaoBaoGxApi;
use yii\base\Exception;
use yii\data\Pagination;
use yii\web\Controller;
use yii\widgets\LinkPager;

class SearchController extends Controller
{

    /**
     * 每页商品数量
     */
    const pageSize = 100;
    /**
     * @author       :   DuYongGao
     * @name         :   actionIndex
     * @description  :
     * @return \yii\web\Response
     * @demo http://dutest.qtk.com/?r=search/index
     */
    public function actionIndex(){
        $data = \Yii::$app->request->get();
        $api = new HelperSearch();
        $json = $api->getData($data);

        //分页
        if($json['er_code'] == 10000){
            $pagination = new Pagination(['totalCount' => $json['data']['total'],'pageSize'=>self::pageSize]);
            $json['pagination'] = LinkPager::widget([
                'pagination' => $pagination,
            ]);
        }

        $api = new HelperSearch();
        $list = $api->getWord();
        if(!empty($list) && count($list) > 1){
            $list = array_slice($list,0,10);
        }

        return $this->render('index',['data_list'=>isset($json['data']['list']) ? $json['data']['list'] : [],'list'=>$list,'pager'=>isset($json['pagination']) ? $json['pagination'] : ""]);
    }

    /**
     * @author       :   DuYongGao
     * @name         :   actionList
     * @description  :
     * @return \yii\web\Response
     * @demo http://dutest.qtk.com/?r=search/list
     */
    public function actionList(){
        $data = \Yii::$app->request->get();
        $api = new HelperSearch();
        if(empty($data['key_word'])){
            $json = $api->getData($data);
        }else{
            $json = $api->getGood($data);
        }

        //分页
        if($json['er_code'] == 10000){
            $pagination = new Pagination(['totalCount' => $json['data']['total'],'pageSize'=>self::pageSize]);
            $json['pagination'] = LinkPager::widget([
                'pagination' => $pagination,
            ]);
        }
        $api = new HelperSearch();
        $list = $api->getWord();
        if(!empty($list) && count($list) > 1){
            $list = array_slice($list,0,10);
        }

        return $this->render('index',['data_list'=>isset($json['data']['list']) ? $json['data']['list'] : [],'list'=>$list,'pager'=>isset($json['pagination']) ? $json['pagination'] : ""]);
    }

    /**
     * @author       :   DuYongGao
     * @name         :   actionList
     * @description  :
     * @return \yii\web\Response
     * @demo http://dutest.qtk.com/?r=search/list
     */
    public function actionWord(){
        $api = new HelperSearch();
        $list = $api->getWord();
        return $this->render('word',['list'=>$list]);
    }

    /**
     * @author       :   DuYongGao
     * @name         :   actionList
     * @description  :
     * @return \yii\web\Response
     * @demo http://dutest.qtk.com/?r=search/list
     */
    public function actionBank(){
        $api = new HelperSearch();
        $json = $api->getBank();

        //分页
        if($json['er_code'] == 10000){
            $pagination = new Pagination(['totalCount' => 100,'pageSize'=>self::pageSize]);
            $json['pagination'] = LinkPager::widget([
                'pagination' => $pagination,
            ]);
        }

        return $this->render('bank',['data_list'=>isset($json['data'])?$json['data']:[],'pager'=>isset($json['pagination']) ? $json['pagination'] : ""]);
    }

    /**
     * @author       :   DuYongGao
     * @name         :   actionDetail
     * @description  : 详情高效转链接口
     * @return \yii\web\Response
     * @demo http://dutest.qtk.com/?r=search/detail&activityId=ae31a42b6ee2428e944a6c6c473f32a8&itemId=544329180225
     */
    public function actionDetail(){
        $data = \Yii::$app->request->get();
        if(empty($data['activityId'])){
            return $this->asJson(['status'=>300,'code'=>"缺少券id"]);
        }
        if(empty($data['itemId'])){
            return $this->asJson(['status'=>300,'code'=>"缺少商品id"]);
        }
        $api = new HelperSearch();
        $json = $api->getDetail($data);
        return $this->asJson($json);
    }
    
    public function actionInfo(){
        $query = SiteInfo::find();
        if($id = \Yii::$app->request->get("id",0)){
            $query->where(['id'=>$id]);
        }
        $model = $query->one();
        if(empty($model)){
            $this->goHome();
        }
        return $this->render('info',[
            'model' => $model
        ]);
    }

    public function actionInfoList(){
        $query = SiteInfo::find();
        $count_query = clone $query;
        $pager = new Pagination(['totalCount' => $count_query->count()]);

        $list = $query->limit($pager->limit)->select(['id','title','create_at'])->offset($pager->offset)->orderBy("id desc")->asArray()->all();
        return $this->render('info-list',[
            'list' => $list,
            'pager' => $pager,
        ]);
    }

    /**
     * 活动页
     * @return string
     */
    public function actionActivity(){
        $this->layout = false;
        return $this->render('activity');
    }
    /**
     * 规则页
     * @return string
     */
    public function actionRule(){
        $this->layout = false;
        return $this->render('rule');
    }

    /**
     * 阿里宣传
     * @return string
     */
    public function actionAli(){
        return $this->render('ali');
    }

    const PID = 'mm_132945362_45254699_528424175';
    public function actionJump(){
        $gid = \Yii::$app->request->get("gid");
        $aid = \Yii::$app->request->get("aid");
        $pic = \Yii::$app->request->get('pic');
        $title = \Yii::$app->request->get('title');
        $pid = self::PID;
        $api = new TaoBaoGxApi();
        $url = "https://uland.taobao.com/coupon/edetail?activityId={$aid}&itemId={$gid}&pid={$pid}";
        $code = null;
        if(Comm::isWx()){
            try{
                $tao['url'] = $url;
                $tao['title'] = $title;
                $tao['pic_url'] = $pic;
                $result = $api->getTaoCode($tao);
                $code = $result;
            }catch (Exception $e){

                if(\Yii::$app->request->isAjax){
                    return $this->asJson(['status'=>300,'data'=>$e->getMessage() ,'is_wx' => Comm::isWx()]);
                }else{
                    $this->render('none');
                }
            }
        }
        $data_coupon = [
            'url' => $url,
            'code' => $code,
        ];

        if(\Yii::$app->request->isAjax){
            return $this->asJson(['status'=>200,'data'=>$data_coupon ,'is_wx' => Comm::isWx()]);
        }else{
            $this->redirect($data_coupon['url']);
        }
        
    }

    public function actionChange(){
        if(\Yii::$app->request->isAjax){
            $url = \Yii::$app->request->post("url");
            if(preg_match('/(http[s]?[a-zA-Z0-9\:\/\.\?\=\&]+)/',$url,$out)){
                $url = $out[1];
                if(!preg_match('/[\?\&]id=(\d+)/',$url,$out)){
                    $curl = new Curl();
                    $re = $curl->get($url);
                    if(preg_match('/(https\:\/\/item\.taobao\.com[^\']+)/',$re->response,$out)){
                        $url = $out[1];
                    }
                }
            }
            if(preg_match('/[\?\&]id=(\d+)/',$url,$out)){
                $gid = $out[1];
                $time = date('Y-m-d');
                $pid = self::PID;
                $key = md5($gid.$time);
                $data_coupon = \Yii::$app->cache->get($key);
                if(empty($data_coupon)){
                    $api = new TaoBaoGxApi();
                    try{
                        $data = $api->transferGx($gid,$pid,false);
                        $url = $data['coupon_click_url'];
                        if(!empty($aid)){
                            $url .= '&activityId='.$aid;
                        }
                        $tao['url'] = $url;
                        $tao['title'] = "优惠商品";
                        $result = $api->getTaoCode($tao);
                        $code = $result;
                        $data_coupon = [
                            'url' => $url,
                            'code' => $code,
                        ];
                        \Yii::$app->cache->set($key,$data_coupon,86400);
                    }catch (Exception $e){

                        if(\Yii::$app->request->isAjax){
                            return $this->asJson(['status'=>300,'data'=>$e->getMessage() ,'is_wx' => Comm::isWx()]);
                        }else{
                            $this->render('none');
                        }
                    }
                }
                return $this->asJson(['status'=>200,'data'=>$data_coupon ,'is_wx' => Comm::isWx()]);
            }else{
                return $this->asJson(['status'=>300,"data"=>"商品链接错误"]);
            }
        }
        return $this->render("change");
    }

    public function actionNone(){
        $api = new TaoBaoGxApi();
        var_dump($api->getTokenCache(false));
    }

    /**
     * 读取券信息
     * @return \yii\web\Response
     */
    public function actionCoupon(){
        return $this->asJson(['status'=>200,'data'=>[]]);
        $aid = \Yii::$app->request->get('aid');
        $gid = \Yii::$app->request->get('gid');
        if(empty($aid) || empty($gid)){
            return $this->asJson(['status'=>300,'code'=>"信息错误"]);
        }
        $key = md5("actionDetail".$gid.$aid);
        $data = \Yii::$app->cache->get($key);
        if(!empty($data)){
            return $this->asJson(['status'=>200,'data'=>$data]);
        }
        $api = new TaoBaoApi();
        try{
            $data = $api->getCoupon($gid,$aid);
        }catch (\Exception $e){
            $data = ['code'=>'err','msg'=>$e->getMessage()];
        }
        \Yii::$app->cache->set($key,$data,3600);
        return $this->asJson(['status'=>200,'data'=>$data]);
    }

    /**
     * 用户保存订单
     * @return string|\yii\web\Response
     */
    public function actionOne(){
        $model = new SiteData();

        if ($model->load(\Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['one_ok', 'id' => $model->id]);
        } else {
            return $this->render('one', [
                'model' => $model,
            ]);
        }
    }
}